package tripx.db.system;

import tripx.db.DbConnector;
import tripx.db.server.DbServer;

/**
 * The class to handle to most of the configuration, and master the common
 * object which exsits in the interaction between modules.
 * 
 * @author zhb
 * 
 */
public class TripxSystem {

	/**
	 * the single instance of this object
	 */
	private static TripxSystem sys;

	private DbConnector connector;

	private DbServer server;

	private SysConfig config;

	/* private constructor */
	private TripxSystem() {
		config = new SysConfig();
		setup();
	}

	public static TripxSystem getInstance() {
		if (sys == null) {
			sys = new TripxSystem();
		}
		return sys;
	}

	/**
	 * start up the database system.
	 */
	public void startup() {
		/* initialize the connector */
		connector.openConnection();
		/* start the service server */
		server.start();
	}

	public void shutdown() {
		/* break out the database connection */
		connector.closeConnection();
		/* shutdown the service serever */
		server.shutdown();
	}

	/**
	 * get the database connector
	 * 
	 * @return
	 */
	public DbConnector getDbConnector() {
		return connector;
	}

	/**
	 * get the global config
	 * 
	 * @return
	 */
	public SysConfig getSystemConfig() {
		return config;
	}

	// -------------------------------------------------------------
	// ------------ setup the connector and the server ------------
	// -------------------------------------------------------------
	private void setup() {
		connector = new DbConnector(config.getUserName(), config.getHost(),
				config.getDbPort(), config.getPassword(), config.getDbName(),
				config.getProtocol(), config.getDriverClass());
		server = new DbServer(config.getPropertyHandlerMapping(),
				config.getServerPort());
	}
}
